package com.yangit.temp.util.pdf.controller;

import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import com.itextpdf.text.pdf.BaseFont;
import com.lowagie.text.DocumentException;

/**
 * Flying Sauser 解决html转pdf问题
 * @author Administrator
 *
 */
public class PdfHtmlController {

	@RequestMapping("/pdf/{projectId}")
	public ModelAndView generatePdf(HttpServletRequest request, HttpServletResponse response,
			@PathVariable String projectId) throws DocumentException, IOException {
		// Project project = this.projectService.getProjectById(projectId);
		ModelAndView mav = new ModelAndView();
//        if (project == null) {   
//            mav.setViewName("forward:/error/page-not-found");   
//            return mav;   
//        }   
		// 中文需转义
		String pdfName = "pdfName";

		response.setHeader("Content-disposition", "attachment;filename=" + pdfName);
		response.setContentType("application/pdf");
		OutputStream os;

		os = response.getOutputStream();

		ITextRenderer renderer = new ITextRenderer();
		// 指定模板地址
		renderer.setDocument("http://localhost/project/preview/" + projectId);

		ITextFontResolver fontResolver = renderer.getFontResolver();
		// 判断系统
		String sysOS="windows";
		if (sysOS.equals("windows")) {
			fontResolver.addFont("C:/Windows/Fonts/ARIALUNI.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
		} else {
			fontResolver.addFont("/usr/share/fonts/TTF/ARIALUNI.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
		}
		renderer.layout();
		renderer.createPDF(os);
		os.close();

		return null;
	}

	@RequestMapping("/preview/{projectId}")
	public ModelAndView pdf(@PathVariable String projectId) {
		// Project project = this.projectService.getProjectById(projectId);
		ModelAndView mav = new ModelAndView();
//		if (project == null) {
//			mav.setViewName("forward:/error/page-not-found");
//			return mav;
//		}
		mav.setViewName("pdf");
//		mav.addObject("project", project);
		return mav;
	}

}
